const fs = require('fs')
const {mkdirsSync, rmdirsSync} = require('./utils')
const Crawler = require("crawler");
// const Restaurant = require("./model/restaurant.js");
const tjs = require('translation.js')
const logger = require('./utils/logger')

var transPromise = function (text, api = 'baidu') {
  return new Promise(function (resolve, reject) {
    if (text === null || text === undefined || text.length === 0) {
      resolve([])
    } else {
      tjs
        .translate({
          text: Array.isArray(text) ? text.join(',') : text,
          from: 'th', // 文本的源语种
          to: 'zh-CN', // 文本的目标语种
          // api
        })
        .then(result => {
          resolve(result.result[0]) // result 的数据结构见下文
        }, err => {
          reject(err)
        })
    }
  });
};

var cPromise = function (url) {
  return new Promise((resolve, reject) => {
    c.queue([{
      uri: url,
      // The global callback won't be called
      callback: function (error, res, done) {
        if (error) {
          reject(error)
        } else {
          resolve(res.$)
          done();
        }
      }
    }]);
  })
}

var transComments = function (comments) {
  let pArr = []
  comments.forEach((v, k) => {
    pArr.push(transPromise(v.title))
    pArr.push(transPromise(v.menu))
    pArr.push(transPromise(v.brand.content))
  })
  return pArr
}

/**
 * 上传图片到七牛
 * @type {UploadFile}
 */
const UploadFile = require('./utils/upload')


const c = new Crawler({
  encoding: null
});

// 设置爬虫代理
// c.on('schedule',function(options){
//     options.proxy = "http://localhost:1080";
// });


var x = {
  name: {type: 'string'}, // 点名
  start: {type: 'number'}, // 评星
  collectionCount: {type: 'number'}, // 收藏数量
  classification: {type: 'string'}, //分类
  mainPic: {type: 'string'}, // 主图
  position: {type: 'object'}, // 位置信息
  tel: {type: 'string'}, // 电话
  menu: {type: 'object'}, // 菜单
  special: {type: 'object'}, // 特别（非必选）
  brandStory: {type: 'object'}, // 特别（非必选）
  imgs: {type: 'array'}, // 餐厅图片
  extraInfo: {type: 'string'}, // 额外信息
  recommend: {type: 'array'}, // 会员推荐
  fit: {type: 'array'}, // 这家店适合
  comments: {type: 'array'}, // 评论
}

c.queue({
  uri: 'https://www.wongnai.com/news/crispy-pork-testing',
  // uri: 'http://127.0.0.1:8080/test.html',
  callback: function (error, res, done) {
    if (error) {
      logger.error(error.stack);
    } else {
      let $$ = res.$;
      let brand = {
        mainPic: '',
        title: '',
        content:[],
        map: {
          name: '',
          location: ''
        }
      }
      //
      brand.mainPic = {
        title: $$('._3zrgJ46ouVPVD8zWaHX0l6 img').attr('title'),
        src: $$('._3zrgJ46ouVPVD8zWaHX0l6 img').attr('title'),
      }

      // title
      brand.title = {
        text: $$('._2AoqKUcdJHPd7RfPOmH1IW h1').text(),
        intro: $$('._2OpAl6NVxwk6F-NHqx4crJ ._2WVT_e39nAf0U6u77zRdcu').text(),
        time: $$('._2OpAl6NVxwk6F-NHqx4crJ ._1wBHFCdy5D4YZ-bDtYQxb_').text(),
      }



      // content
      $$('._198nXlXoiYBkCKbP5aX04J').children().each((k, v) => {
        let $v = $$(v)
        let tag = $v[0].tagName
        if(tag === 'p') {
          brand.content.push({
            tag: 'p',
            text: $v.text()
          })
        }


        if(tag === 'h2') {
          brand.content.push({
            tag: 'h2',
            seq: $v.find('.seq').text(),
            text: $v.find('b').text()
          })
        }

        if(tag === 'figure') {
          brand.content.push({
            tag: 'figure',
            src: $v.find('img').attr('src'),
            title: $v.find('img').attr('alt')
          })
        }


        if(tag === 'div') {
          $$(v).find('figure').each((key, value) => {
            brand.content.push({
              imgs: {
                src: $v.find('img').attr('src'),
                title: $v.find('img').attr('alt')
              }
            })
          })
        }
      })

      // map
      brand.map = {
        name: $$('._1MB1vj7GPnORlUNcPA-jBj').text(),
        location: $$('._3Ca2TqwtDlEJcEZrmPbZ_W ._3YPfNh8cCEjUf8VEeesPXU').html()
      }

      Promise.all(
        [
          transPromise($$('._2AoqKUcdJHPd7RfPOmH1IW h1').text()),
          transPromise($$('._2OpAl6NVxwk6F-NHqx4crJ ._2WVT_e39nAf0U6u77zRdcu').text()),
          transPromise($$('._2OpAl6NVxwk6F-NHqx4crJ ._1wBHFCdy5D4YZ-bDtYQxb_').text())
        ]
      ).then(data => {
        brand.title = {
          text: data[0],
          intro: data[1],
          time: data[2],
        }


        let contentTransArr = []
        let contentTransIdx = []
        brand.content.forEach((v, k) => {
          let tag = v.tag
          if(tag === 'p') {
            contentTransArr.push(transPromise(v.text))
            contentTransIdx.push(k)
          }

          if(tag === 'h2') {
            contentTransArr.push(transPromise(v.text))
            contentTransIdx.push(k)
          }
        })

        Promise.all(contentTransArr).then(res => {
          // console.dir(res)
          res.forEach((v, k) => {
            brand.content[contentTransIdx[k]].text = v
          })
          console.dir(brand)
        })
      })
      done();
    }
  }
});



